<template>
    <!-- <div class="dept">
        <button @click="getDept">向后端请求数据</button>
    <button @click="is_show">新增部门</button>
    <div class="show_Add" v-if="show_Add">
        部门名称<input type="text" v-model="dept_text"><button @click="Add">确定</button>
    </div>
    <table class="Dept">
        <caption class="title">部门表</caption>
        <thead>
            <tr>
            <th>id</th>
            <th>部门名称</th>
            <th>创建时间</th>
            <th>更新时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
            <tr v-for="(item) in dataArr" :key="item.id">
            <td v-for="(i) in item">
                {{ i }}
                <div class="show_change" v-if="i==item.name&&show_change&&dept_index==item.id">
                    <input type="text" v-model="dept_name"><button @click="Update(item.id)">确定</button>
                </div>
            </td>
            <td><button @click="deleteById(item.id)">删除</button><button @click="changeShow(item.id)">修改</button></td>
        </tr>
        </tbody>
    </table>
    </div> -->
    
    <!-- <div class="job">
        <button @click="getJob">向后端请求数据</button>
        <button @click="is_showJob">新增职位</button>
        <div class="updateJob" v-if="showInsertJob">
            职位名称：<input type="text" v-model="jobName">
            <button @click="saveInsertJob">保存</button>
        </div>
        <table class="Job">
            <caption class="title">职位表</caption>
            <thead>
                <tr>
                    <th>id</th>
                    <th>职位</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="item in JobArr" :key="item.id">
                    <td>{{ item.id }}</td>
                    <td>
                        {{ item.name }}
                        <div class="JobUpdate" v-if="showJob&&item.id==indexJob">
                            <input type="text" v-model="updateJob">
                            <button @click="saveUpdateJob(item.id)" >保存</button>
                        </div>
                        
                    </td>
                    <td>
                        <button @click="delJob(item.id)">删除</button>
                        <button @click="isShowUpdateJob(item.id)">修改</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div> -->


    <div class="emp">
        <button @click="getEmp">向后端请求数据</button>
    <div class="serach">
        姓名<input type="text" v-model="emp_name">
        <label for="genders">性别</label>  
  
        <select v-model="emp_gender" id="genders">  
        <option value="1">男</option>  
        <option value="2">女</option>  
        
        </select>

        <button @click="search">查询</button>
    </div>
    <button @click="empDelete">批量删除</button>
    <div class="new">
        <button @click="show_emp">新增员工</button>
        <div v-if="showAddEmp" class="newEmp">
        用户名：<input type="text" v-model="usernameText">
        员工姓名：<input type="text" v-model="nameText">
        性别：<select v-model="genderText" class="genders">  
                <option value="1">男</option>  
                <option value="2"selected>女</option>  
            </select>
        头像：<div class="img">
            <form @submit.prevent="handleSubmit">  
            <input type="file" id="avatar" @change="onFileChange" />  
            <button type="submit">提交</button>  
            </form>  
            <p v-if="message">{{ message }}</p>  
            <img :src="imgText">
            </div>
        职位：<select v-model="jobText" id="job-text">
                <option v-for="item in JobArr" :key="item.id" :value="item.id">{{ item.name }}</option>
            </select>
            <br>
        归属部门：<select v-model="deptText" id="dept-text">  
                    <option :value=item.id v-for="item in deptName" :key="item.id">{{ item.name }}</option>
                </select>
        <button @click="save">保存</button>
        </div>
        
    </div>
    
    <table class="Emp">
        <caption class="title">员工表</caption>
        <thead>
            <tr>
            <th><div>全选<input type="checkbox" v-model="allcheck"></div></th>
            <th>id</th>
            <th>用户名</th>
            <th>密码</th>
            <th>姓名</th>
            <th>性别</th>
            <th>头像</th>
            <th>职位</th>
            <th>入职日期</th>
            <th>部门</th>
            <th>创建时间</th>
            <th>更新时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
            <tr v-for="item in EmpArr" :key="item.id">
                <td><input type="checkbox" v-model="deleteArr" :value=item.id></td>
                <td>{{ item.id }}</td>
                <td>{{ item.username }}</td>
                <td>{{ item.password }}</td>
                <td>{{ item.name }}</td>
                <td>{{ item.gender }}</td>
                <td><img :src="item.image" alt=""></td>
                <td>{{item.jobName }}</td>
                <td>{{ item.entrydate }}</td>
                <td>{{ item.deptName }}</td>
                <td>{{ item.createTime }}</td>
                <td>{{ item.updateTime }}</td>
                <td>
                    <button @click="updateEmp(item.id,item.username,item.name,item.gender,item.image,item.jobId,item.deptId)">修改</button>
                    <button @click="deleteEmp(item.id)">删除</button>
                </td>
            </tr>
        </tbody>
    </table>
    <p>总共有{{ count }}条数据</p>
    <div class="updateEmp" v-if="showUpdateEmp">
        用户名：<input type="text" v-model="usernameText">
        员工姓名：<input type="text" v-model="nameText">
        性别：<select v-model="genderText" class="genders">  
                <option value="1">男</option>  
                <option value="2"selected>女</option>  
            </select>
        头像：<div class="img">
            <form @submit.prevent="handleSubmit">  
            <input type="file" id="avatar" @change="onFileChange" />  
            <button type="submit">提交</button>  
            </form>  
            <p v-if="message">{{ message }}</p>  
            <img :src="imgText">
            </div>
        职位：<select v-model="jobText" id="job-text">
                <option v-for="item in JobArr" :key="item.id" :value="item.id">{{ item.name }}</option>
            </select>
            <br>
        归属部门：<select v-model="deptText" id="dept-text">  
                    <option :value=item.id v-for="item in deptName" :key="item.id">{{ item.name }}</option>
                </select>
        <button @click="saveUpdate">保存</button>
        </div>
    </div>
</template>





<script setup lang="ts" name="index">
import {ref,onMounted,reactive,watch} from 'vue';
import axios from 'axios';

let showJob=ref(false);
let updateJob=ref("");
let indexJob=ref(-1);
function isShowUpdateJob(index: number){
    showJob.value=true;
    indexJob.value=index;
}


async function saveUpdateJob(id:number){

    let {data} =await axios.put("http://localhost:8080/jobs",{
        id: id,
        name: updateJob.value
    })

    getJob();
    showJob.value=false;
}


let showInsertJob=ref(false);
function is_showJob(){
    showInsertJob.value=true;
}


async function saveInsertJob(){
    
    let {data}=await axios.post("http://localhost:8080/jobs",{
        name: jobName.value
    })
    getJob();
    showInsertJob.value=false;
}

let jobName=ref("");
async function delJob(id:number){
    let data=await axios.delete("http://localhost:8080/jobs/"+id);
    
    getJob();
    alert("删除职位成功");
}


interface JobData {
    id: number,
    name: string
}

let JobArr=ref<JobData[]>([]);
async function getJob(){
    let {data}=await axios.get("http://localhost:8080/jobs");
    JobArr.value=data.data;
}
let showUpdateEmp=ref(false);
let id_index=ref(0);
let deptName=ref<DeptData[]>([]);
onMounted(()=>{
    getEmp();
})
function updateEmp(id:number,username:string,name:string,gender:string,img:string,job:number,dept:number){
    id_index.value=id;
    usernameText.value=username;
    nameText.value=name;
    genderText.value=gender;
    imgText.value=img;
    jobText.value=job;
    deptText.value=dept;
    showUpdateEmp.value=true;
}
async function saveUpdate(){
    let gender=(genderText.value=="男")?"1":"2";
    // console.log(id_index.value,usernameText.value,nameText.value,gender,deptText.value,jobText.value,imgText.value)
    let {data} =await axios.put("http://localhost:8080/emps",{
        id: id_index.value,
        username: usernameText.value,
        name: nameText.value,
        gender: gender,
        deptId: deptText.value,
        job: jobText.value,
        image: imgText.value
    })
    getEmp();
    showUpdateEmp.value=false;
}
function deleteEmp(index: number){
    deleteArr.value.push(index);
    empDelete();
}

const file = ref<File | null>(null);  
const message = ref<string | null>(null);  
  
    const onFileChange = (event: Event) => {  
      const input = event.target as HTMLInputElement;  
      if (input.files && input.files.length > 0) {  
        file.value = input.files[0];  
      }  
    };  
  
    const handleSubmit = async () => {  
      if (!file.value) {  
        message.value = '请选择一个文件上传';  
        return;  
      }  
  
      const formData = new FormData();  
      formData.append('image', file.value);  
  
      try {  
        const {data} = await axios.post('http://localhost:8080/upload', formData, {  
          headers: {  
            'Content-Type': 'multipart/form-data',  
          },  
        });  
  
        // 根据服务器响应设置message  
        message.value = data.message || '上传成功';  
        imgText.value=data.data;
        // 可选：重置file和message  
        // file.value = null;  
        // message.value = null;  
  
      } catch (error:any) {  
        if (axios.isAxiosError(error)) {  
          message.value = `上传出错: ${error.response?.data.message || error.message}`;  
        } else {  
          message.value = `上传出错: ${error.message}`;  
        }  
      }  
    }
let showAddEmp=ref(false);
let usernameText=ref("");
let nameText=ref("");
let genderText=ref("");
let deptText=ref();
let jobText=ref();
let imgText=ref("");
function show_emp(){
    showAddEmp.value=true;
    // console.log("deptName",deptName.value);
}

async function save(){
    // console.log(usernameText.value)
    // console.log(nameText.value)
    // console.log(genderText.value)
    // console.log(deptText.value)
    // console.log(jobText.value)
    // console.log(imgText.value)
    let {data} =await axios.post("http://localhost:8080/emps",{
        username: usernameText.value,
        name: nameText.value,
        gender: genderText.value,
        deptId: deptText.value,
        job: jobText.value,
        image: imgText.value
    })
    getEmp();
    showAddEmp.value=false;
}

interface DeptData{
    id: number,
    name: string,
    createTime: string,
    updateTime: string
}
interface EmpData{
    id: number,
    username: string,
    password: string,
    name: string,
    gender: string,
    image: string,
    jobId: number,
    jobName: string,
    entrydate:string,
    deptId:number,
    deptName:string,
    createTime:string,
    updateTime:string,
}
let dept_index=ref(-1);
let show_change=ref(false);
let show_Add=ref(false);
let dept_text=ref("");
let dept_name=ref("");
function is_show(){
    show_Add.value=true;
    
}
async function Add(){
    show_Add.value=false;
    let {data}=await axios.post("http://localhost:8080/depts",{
        name: dept_text.value
    })
    getDept();
    console.log(data);
    dept_text.value="";
}
async function Update(id: number){
    show_change.value=false;
    let dept_date={
        id:id,
        name: dept_name.value
    }
    let {data}=await axios.put("http://localhost:8080/depts",dept_date);
    // console.log(data.data);
    dept_name.value="";
    getDept();
}
function changeShow(index: number){
    show_change.value=true;
    dept_index.value=index;
}
async function deleteById(id :number){
    let {data}=await axios.delete("http://localhost:8080/depts/"+id);
    // console.log(id);
    alert("删除成功");
    // console.log(data.data);
    // dataArr.value=data.data;
    getDept();
}



let dataArr=ref<DeptData[]>([])
// onMounted(getEmp);
async function getDept() {
    let {data}= await axios.get("http://localhost:8080/depts");
    // console.log(data.data);
    dataArr.value=data.data;
    deptName.value=data.data;
    // for(let i=0;i<dataArr.value.length;i++){
    //     console.log(dataArr.value[i]);
    // }
    // console.log("deptName",deptName.value);
}


let count=ref(0);
let emp_name=ref("");
let emp_gender=ref("");
let EmpArr=ref<EmpData[]>([]);
async function getEmp(){
    let {data}=await axios.get("http://localhost:8080/emps");
    // console.log(data.data);
    count.value=data.data.total;
    EmpArr.value=data.data.rows;
    changeGender();
    
}
function changeGender(){
    for(let i in EmpArr.value){
        if(EmpArr.value[i].gender=="1"){
            EmpArr.value[i].gender="男";
        }
        else{
            EmpArr.value[i].gender="女";
        }
    }
}
async function search(){
    let params={
        name: emp_name.value,
        gender: emp_gender.value
    }
    
    let {data}=await axios.get("http://localhost:8080/conditionemps",{
        params: params
    })
    EmpArr.value=data.data.rows;
    count.value=data.data.total;
    changeGender();
}

const deleteArr=ref<number[]>([]);

async function empDelete(){
    const url = 'http://localhost:8080/emps';  
        const ids = deleteArr.value;  
        const queryString = ids.map(id => `ids=${id}`).join('&'); // 手动构建查询字符串  
        const fullUrl = `${url}?${queryString}`;  
        console.log(fullUrl);
        const response = await axios.delete(fullUrl);  
        getEmp();
}

let allcheck=ref(false);
watch(allcheck,(val)=>{
    if(val){
       deleteArr.value=EmpArr.value.map(emp=>emp.id);
    }
    else{
        deleteArr.value=[];
    }
})
watch(deleteArr,(val)=>{
    if(val.length==count.value){
        allcheck.value=true;
    }
})
function Test(){
    console.log(allcheck.value);
}

</script>



<style scoped>
.job{
    border: 2px solid black;
    margin-bottom: 100px;
}
.emp{
    border: 2px solid black;
    .newEmp{
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        background-color: pink;
        z-index: 9999;
        border: 1px solid black;
        overflow-y: auto;
        max-height: 500px;
    }
    .updateEmp{
        position: fixed;
        
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        background-color: pink;
        z-index: 9999;
        border: 1px solid black;
        input{
            display: block;
        }
    }
}
.dept{
    border: 2px solid black;
    margin-bottom: 100px;
}
.Dept{
     
     width: 100%;  
     border-collapse: collapse;  
    
    th, td {  
        border: 1px solid #000000;  
        padding: 8px;  
        text-align: center;
    }  
}
.Emp{
     
     width: 100%;  
     border-collapse: collapse;  
    
    th, td {  
        border: 1px solid #000000;  
        padding: 8px;  
        text-align: center;
    }  
}
.Job{
     
     width: 100%;  
     border-collapse: collapse;  
    
    th, td {  
        border: 1px solid #000000;  
        padding: 8px;  
        text-align: center;
    }  
}
.newEmp{
    input{
        display: block;
    }
}
.title{
    font-size: 30px;
    font-weight: 700;
}
</style>
